<template>
	<view class="craftsmanAdd">
		<u-form :model="form" ref="form1">
			<view class="top" v-if="form.type == 1 && !optionData.entrance">
				<view class="f32 fb">
					个人信息
				</view>
				<u-form-item label=" 姓 名 " prop="name" labelWidth="200">
					<u-input v-model="form.name" clearable placeholder="请输入真实姓名" />
				</u-form-item>
				<!-- <u-form-item label="身份证" prop="number" labelWidth="200">
					<u-input maxlength="18" v-model="form.number" type="idcard" clearable placeholder="请输入身份证号码" />
				</u-form-item> -->
				<u-form-item label="手机号" prop="mobile" labelWidth="200">
					<u-input v-model="form.mobile" maxlength="11" type="number" clearable placeholder="请输入手机号码" />
				</u-form-item>
				<u-form-item v-if="form.type == 1" label="工种类型" prop="work_type_ids" labelWidth="200">
					<u-input v-model="selectData.work_type_ids" type="select" placeholder="请选择工种类型"
						@click="inputSelect('work_type_ids')" />
				</u-form-item>
			</view>
			<view class="top" v-if="form.type == 2 && !optionData.entrance">
				<view class="f32 fb mt32">
					企业信息
				</view>
				<u-form-item label-position="top" label="上传公司营业执照" prop="business_image" labelWidth="200">
					<view class="grid grid-square flex-sub">
						<view class="bg-img border" v-if="form.business_image">
							<image :src="$wanlshop.oss(form.business_image)" mode="aspectFill"
								@click="previewImage(-1)">
							</image>
							<view class="cu-tag bg-red" @tap.stop="delImg('business_image',-1)"><text
									class="wlIcon-31guanbi"></text>
							</view>
						</view>

						<view class="bg-img dashed border" @tap="chooseImage('business_image',1)">
							<text class="wlIcon-31paishe"></text>
						</view>
					</view>
				</u-form-item>

				<u-form-item label="企业名称" prop="name" labelWidth="200">
					<u-input v-model="form.name" clearable placeholder="请输入企业名称" />
				</u-form-item>
				<u-form-item label="社会信用代码" prop="number" labelWidth="200">
					<u-input v-model="form.number" type="idcard" clearable placeholder="请输入社会信用代码" />
				</u-form-item>
				<u-form-item label-position="top" label="企业介绍" prop="company_des" labelWidth="200">
					<u-input v-model="form.company_des" clearable height='200' type="textarea" placeholder="请填写企业介绍" />
				</u-form-item>
				<u-form-item label="手机号" prop="mobile" labelWidth="200">
					<u-input v-model="form.mobile" maxlength="11" type="number" clearable placeholder="请输入手机号码" />
				</u-form-item>
			</view>
			<view class="top" v-if="optionData.entrance == 'bj' ">
				<view class="f32 fb">
					{{form.type==2?'公司信息':'个人信息'}}
				</view>
				<view class="mt32 flex_sb flex_ac">
					<view class="f28 c3d">
						头像
					</view>
					<view class="flex_ac" @click="chooseImage('avatar',1)">
						<image class="imgavatar" :src="$wanlshop.oss(form.avatar)" mode=""></image>
						<view class="info f24 ml12">
							更换
						</view>
					</view>

				</view>
				<u-form-item label=" 昵称 " prop="name" labelWidth="200">
					<u-input style="text-align: right;" v-model="form.name" placeholder="请输入真实姓名" />
				</u-form-item>

			</view>
			<view class="top mt32" v-if="optionData.entrance== 'bj'">
				<view class="f32 fb">
					服务信息
				</view>

				<u-form-item :label="form.type == 2 ?'建立时间':'从业时间'" prop="begin_work_time" labelWidth="200">
					<u-input v-model="selectData.begin_work_time" type="select" placeholder="请选择从业时间"
						@click="inputSelect('begin_work_time')" />
				</u-form-item>
				<u-form-item label-position="top" label="服务内容（选填）" prop="" labelWidth="200">
					<u-input v-model="form.service_content" clearable height='200' type="textarea"
						placeholder="请填写您的优势以及擅长的具体服务内容" />
				</u-form-item>
			</view>
			<view class="top mt32" v-if="optionData.entrance== 'bj'">
				<view class="f32 fb">
					上传资质/经验证明
				</view>
				<view class="sczgs mt20">
					您可上传资格证书，其他同类型平台的“服务订单数”、“服务分数”，现场施工等图片来作为您的经验证明
				</view>
				<u-form-item label-position="top" label="上传图片(最多4张)" prop="file_images" labelWidth="200">
					<view class="grid grid-square flex-sub">
						<block v-for="(i,k) in form.file_images" :key="k">
							<view class="bg-img border">
								<image :src="$wanlshop.oss(i)" mode="aspectFill" @click="previewImage(k)">
								</image>
								<view class="cu-tag bg-red" @tap.stop="delImg('file_images',k)"><text
										class="wlIcon-31guanbi"></text>
								</view>
							</view>
						</block>

						<view class="bg-img dashed border" @tap="chooseImage('file_images',4)">
							<text class="wlIcon-31paishe"></text>
						</view>
					</view>
				</u-form-item>
			</view>
			<view class="btnSub mt20">
				<button class="btn" @click="submit" :loading="btnLoading" open-type="liveActivity">
					{{ optionData.entrance ? '完善信息':'立即入驻'}}
				</button>
			</view>

		</u-form>
		<u-select v-model="selectShow" value-name="id" label-name="name" :mode="selectMode" :list="selectList"
			@confirm="confirmSelect">
		</u-select>
		<u-popup border-radius="30" v-model="showPopup" mode='bottom'>
			<view class="BoxPopup">
				<view class="flex_ac">
					<view class="f32 fb c3d flex1 tac ml12">
						选择工种类型（可多选）
					</view>
					<view @click="showPopup=false">
						<u-icon name="close" size="30"></u-icon>
					</view>
				</view>
				<scroll-view scroll-y="true" style="height: 95%;">
					<u-checkbox-group @change="checkboxGroupChange" wrap>
						<u-checkbox size="50" label-size='40' v-model="item.checked" v-for="(item, index) in selectList"
							:key="index" :name="item.id">
							<view class="tar mt12">
								{{item.name}}
							</view>
						</u-checkbox>
					</u-checkbox-group>
				</scroll-view>
				<view class="mt32 flex_ac">
					<u-button type="primary" @click="checkedAll">全选</u-button>
					<view class="flex1 ml24">
						<u-button type="error" @click="showPopup=false">确定选择</u-button>
					</view>
				</view>
			</view>
		</u-popup>
		<u-calendar v-model="showCalendar" :mode="modeCalendar" @change='changeCalendar'></u-calendar>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				form: {
					avatar: '',
					type: 1,
					name: '',
					number: '',
					mobile: '',
					work_type_ids: '',
					begin_work_time: 2000,
					file_images: [],
					business_image: '',
					company_des: '',
					service_content: '',
					lon: '',
					lat: '',
					citycode: '',
					address: '',
				},
				optionData: {},
				rules: {
					name: [{
						required: true,
						message: '请输入姓名',
						trigger: ['blur']
					}],
					mobile: [{
						required: true,
						message: '请输入手机号',
						trigger: ['blur']
					}],

				},
				selectData: {
					begin_work_time: '2000 年',
					work_type_ids: '',
				},
				showPopup: false,
				showCalendar: false,
				modeCalendar: 'date', //date-为单个日期，range-为选择日期范围
				selectType: '',
				selectList: [],
				selectShow: false,
				selectMode: 'single-column',
				btnLoading: false,
			}
		},
		onLoad(option) {

			this.form.type = option.type
			this.optionData = option
			if (option.type == 2) {
				// this.rules.name[0].message = '请输入企业名称'
				// this.rules.number[0].message = '请输入社会信用代码'
				uni.setNavigationBarTitle({
					title: '公司信息'
				});
			} else {
				uni.setNavigationBarTitle({
					title: '个人信息'
				});
			}

			this.getAuth()
		},
		onReady() {
			this.$refs.form1.setRules(this.rules);
			this.form.mobile = uni.getStorageSync('wanlshop:user').mobile
		},
		methods: {
			getAuth() {
				this.$api.post({
					url: '/worker/user/getAuth',
				}).then(res => {
					if (res) {
						res.begin_work_time = res.begin_work_time.toString()
						res.file_images = res.file_images ? res.file_images : []
						res.business_image = res.business_image ? res.business_image : ''
						this.form = Object.assign(this.form, res)
						this.form.type = this.optionData.type

						this.selectData.begin_work_time = res.begin_work_time + ' 年'
						this.selectData.work_type_ids = res.work_type_text.join(',')
						if (this.form.begin_work_time == 0) {
							this.form.begin_work_time = 2000
							this.selectData.begin_work_time = '2000 年'
						}
						if (this.form.type === 1) {
							// 个人信息模式下，工种类型为必填项
							this.rules.work_type_ids = [{
								required: true,
								message: '请选择工种类型',
								trigger: ['change']
							}]
						} else {
							// 企业信息模式下，移除工种类型的必填验证
							delete this.rules.work_type_ids
						}
						this.$refs.form1.setRules(this.rules)
					}
					//状态:status0=待审核,1=审核通过,2=审核未通过
				})
			},
			async submit() {
				console.log(this.form);
				const shouldProceed = await this.$wanlshop.setrequestSubscribeMessage([
					'TQcWNNu7Mlp-G9XUMpA7xZoSqmVAdvFHJ9fZLv1HLGQ',
				])
				if (shouldProceed) {
					if (this.form.avatar == '') {
						delete this.form.avatar
					}
					this.$refs.form1.validate((valid) => {
						console.log(valid);
						if (valid) {
							this.$api.post({
								url: '/worker/user/auth',
								data: this.form,
								success: res => {
									if (this.optionData.entrance == 'bj') {

										uni.showModal({
											title: '提交成功',
											content: '审核完成自动补充更新信息',
											success: function(res) {
												if (res.confirm) {
													if (this.form.avatar) {
														uni.navigateBack({
															delta: 1
														})
													}

												} else if (res.cancel) {}
											}
										});


										return
									}
									this.$wanlshop.to('/pages/craftsman/auditStatus')
								}
							})
						}
					})
				}

			},
			checkboxGroupChange(i) {
				this.form.work_type_ids = i.join(',')
				let work_type_ids = []
				this.selectList.forEach(a => {
					i.forEach(b => {
						if (a.id == b) {
							work_type_ids.push(a.name)
						}
					})
				})
				this.selectData.work_type_ids = work_type_ids.join(',')

			},
			checkedAll() {
				if (this.form.work_type_ids.length !== this.selectList.map(a => a.id).join(',').length) {
					this.form.work_type_ids = this.selectList.map(a => a.id).join(',')
					this.selectList.map(val => {
						val.checked = true;
					})
				} else {
					this.form.work_type_ids = ''
					this.selectList.map(val => {
						val.checked = false;
					})
				}

			},
			inputSelect(type) {
				this.selectType = type
				if (type == 'work_type_ids') {

					this.getWorkerTypeList()
				}
				if (type == 'begin_work_time') {
					let a = []
					for (let i = 1970; i < 2026; i++) {
						a.push({
							id: i.toString(),
							name: i + ' 年'
						})
					}
					this.selectList = a
					this.selectShow = true
				}
			},

			getWorkerTypeList() {
				this.$api.get({
					url: '/worker/user/workerTypeList',
				}).then(res => {
					res.forEach(a => {
						a.checked = false
					})
					this.selectList = res
					this.showPopup = true
				})
			},

			confirmSelect(i) {
				console.log(i);
				this.selectData[this.selectType] = i[0].label
				this.form[this.selectType] = i[0].value.toString()
			},
			changeCalendar(i) {
				this.form[this.selectType] = i.result
			},
			chooseImage(key, key1) { //选择图片
				console.log('--')
				let that = this
				uni.chooseImage({
					sourceType: ["camera", "album"],
					sizeType: "compressed",
					count: key1,
					success: res => {
						uni.showLoading({
							title: '上传中...'
						})
						this.$api.get({
							url: '/wanlshop/common/uploadData',
							success: updata => {
								for (let i = 0; i < res.tempFilePaths.length; i++) {
									// 读取图片宽高
									uni.getImageInfo({
										src: res.tempFilePaths[i],
										success: image => {
											this.$api.upload({
												url: updata.uploadurl,
												filePath: image.path,
												name: 'file',
												formData: updata.storage ==
													'local' ? null : updata
													.multipart,
												success: data => {
													if (key ==
														'file_images') {
														if (this.form
															.file_images
															.length >=
															4) {
															uni.hideLoading()
															return
														} else {
															this.form
																.file_images
																.push(data
																	.url)
														}
													}
													if (key ==
														'business_image') {
														this.form
															.business_image =
															data.url
														this.getocrBusiness(
															data.url)

													}
													if (key ==
														'avatar') {
														this.form
															.avatar =
															data.url
													}


													uni.hideLoading()
												}
											});
										}
									});
								}
							}
						});
					}
				})
			},
			getocrBusiness(url) {
				let that = this
				that.$api.post({
					url: '/common/ocrBusiness',
					data: {
						image: this.$wanlshop.oss(url)
					},
					loadingTip: '上传中...',
					success: imgdata => {
						this.form.name = imgdata.Name
						this.form.number = imgdata.RegNum
						this.form.company_des = imgdata.Business
						// this.form.service_content = imgdata.Business
						this.selectData.begin_work_time = imgdata.SetDate.slice(0, 5)
						this.form.begin_work_time = imgdata.SetDate.slice(0, 4)
						this.addressAna(imgdata.Address)
					}
				})
			},
			addressAna(address) {
				this.$api.get({
					url: '/common/addressAna?address=' + address,
					loadingTip: '加载中...',
					success: res => {

						let data = res.result
						this.form.address = address;
						this.form.lon = data.location.lng
						this.form.lat = data.location.lat
						this.form.citycode = data.ad_info.adcode.slice(0, 4) + '00';
						this.form.adcode = data.ad_info.adcode
						this.form.city = data.address_components.city;
						console.log(this.form);

					}
				})
			},
			previewImage(k) {
				let index = k
				let imgArr = [];
				imgArr = this.form.file_images.map(a => this.$wanlshop.oss(a))
				if (k == -1) {
					imgArr = [this.$wanlshop.oss(this.form.business_image)]
					index = 0
				}

				uni.previewImage({
					urls: imgArr,
					current: index,
					indicator: 'number'
				});
			},
			delImg(type, k) {
				console.log(k);
				if (type == 'business_image') {
					this.form.business_image = null
					return
				}
				if (type == 'file_images') {
					this.form.file_images.splice(k, 1)
				}
			},

		}
	}
</script>

<style lang="scss" scoped>
	.imgavatar {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
	}

	.cu-tag {
		width: 40rpx;
		height: 40rpx !important;
	}

	.BoxPopup {

		// padding-bottom: env(safe-area-inset-bottom);
		padding: 40rpx 60rpx 140rpx;
		height: 70vh;
		overflow: hidden;

		.quxuan {
			width: 120rpx;
			height: 60rpx;
			text-align: center;
			margin: 0;
			padding: 0;
			font-size: 24rpx;
			margin-bottom: 20rpx;
		}
	}

	.btnSub {
		width: 100vw;
		height: 140rpx;
		position: fixed;
		bottom: 0;
		display: flex;
		align-items: center;
		justify-content: center;
		background: #fff;
		z-index: 2;
		padding-bottom: env(safe-area-inset-bottom);

		.btn::after {
			border: none;
		}

		.btn {
			width: 568rpx;
			height: 80rpx;
			font-size: 40rpx;
			background: #FD5241;
			border-radius: 8rpx 8rpx 8rpx 8rpx;
			font-family: PingFang SC, PingFang SC;
			font-weight: 400;
			line-height: 80rpx;
			color: #FFFFFF;
			margin-top: -20rpx;
			border-radius: 200rpx 200rpx 200rpx 200rpx;

			button {
				background: #FD5241;
			}
		}
	}

	.craftsmanAdd {
		padding-bottom: 160rpx;

		.top {
			background: #fff;
			padding: 32rpx;
		}

		.sczgs {
			background: #E7EEFF;
			border-radius: 12rpx 12rpx 12rpx 12rpx;
			padding: 18rpx 24rpx;
			font-size: 24rpx;
			color: #707070;
		}

		.border {
			border: 2px solid #DDDDDD;
			border-radius: 12rpx;
		}

		.bg-img {
			width: 160rpx;
			height: 160rpx;
		}

		.grid.grid-square .bg-img {
			margin: 0 0 12rpx 12rpx;
			border-radius: 12rpx;
		}
	}
</style>